﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Net.Sockets;
using System.ComponentModel;
using VmcRemote.Common.Interfaces;
using System.Threading;

namespace VmcRemote.Common
{
    public class Remote : IDisposable
    {
        private IConnection connection;
        private IMediaCenter server;

        public event EventHandler<RemoteErrorEventArgs> ErrorOccurred;

        public Remote(IConnection connection, IMediaCenter server)
        {
            if (connection == null) throw new ArgumentNullException("connection");
            if (server == null) throw new ArgumentNullException("server");

            this.connection = connection;
            this.server = server;
        }

        protected virtual void OnErrorOccurred(Exception ex)
        {
            if (ErrorOccurred != null)
                ErrorOccurred(this, new RemoteErrorEventArgs(ex));
        }

        public void ExecuteCommand(RemoteCommand command)
        {
            ThreadPool.QueueUserWorkItem((c) => ExecuteCommandInternal((RemoteCommand)c), command);
        }

        private void ExecuteCommandInternal(RemoteCommand command)
        {
            try
            {
                // Use the connection to execute the command by passing it the raw text provided by the server.
                connection.SendCommand(server.GetCommandString(command));
            }
            catch (Exception ex)
            {
                OnErrorOccurred(ex);
            }
        }

        #region IDisposable Members

        public void Dispose()
        {
            if (connection != null)
                connection.Dispose();
        }

        #endregion
    }
}
